package cn.wzptsoft.mall.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.wzptsoft.mall.pojo.Address;
import cn.wzptsoft.mall.pojo.Theme;
import cn.wzptsoft.mall.pojo.User;
import cn.wzptsoft.mall.pojo.dto.UserSaveDto;
import cn.wzptsoft.mall.pojo.result.Result;
import cn.wzptsoft.mall.service.IAddressService;
import cn.wzptsoft.mall.service.IThemeService;
import cn.wzptsoft.mall.service.IUserService;
import cn.wzptsoft.mall.utils.JWTUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping
@Slf4j
@Tag(name = "用户相关接口")
@RequiredArgsConstructor
public class UserController {

    private final IUserService iUserService;

    private final JWTUtil jwtUtil;

    private final IAddressService iAddressService;

    @PutMapping("/user")
    @Operation(summary = "新增用户")
    public Result add(@RequestBody UserSaveDto userdto){
        log.info("新增用户，{}",userdto);
        User user = BeanUtil.copyProperties(userdto, User.class);
        iUserService.saveUser(user);
        return Result.ok();
    }


    @PostMapping("/user/login")
    @Operation(summary = "用户登录")
    public Result login(String username,String password){
        log.info("用户登陆：账号：{}，密码：{}",username,password);
        Integer userId=iUserService.login(username,password);
        //生成jwt
        HashMap<String, Object> map=new HashMap<>();
        map.put("token",userId);
        String jwt = jwtUtil.createToken(map);

        java.util.Map m=new HashMap<>();
        m.put("token",jwt);


        return Result.ok(m);
    }

    @PostMapping("/user/loginout")
    @Operation(summary = "用户登录")
    public Result loginOut(){
        iUserService.loginout();
        return Result.ok();
    }

    @PostMapping("/user/delAddress")
    @Operation(summary = "删除地址")
    public Result delAddressApi(Long id){
        iAddressService.removeById(id);
        return Result.ok();
    }

    @PostMapping("/user/editAddress")
    @Operation(summary = "编辑地址")
    public Result editAddress(@RequestBody Address address){
        iAddressService.updateById(address);
        return Result.ok();
    }

    @PostMapping("/user/addAddress")
    @Operation(summary = "编辑地址")
    public Result addAddress(@RequestBody Address address){
        iAddressService.add(address);
        return Result.ok();
    }

}
